<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <title>商城后台</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/lib/layui-v2.5.5/css/layui.css}" media="all">
    <link rel="stylesheet" th:href="@{/css/public.css}" media="all">
    <link rel="stylesheet" th:href="@{/lib/layui_ext/dtree/dtree.css}" >
    <link rel="stylesheet" th:href="@{/lib/layui_ext/dtree/font/dtreefont.css}" >
</head>
<body>

<span th:replace="common_page::common"></span>

<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" id="userSearchForm" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">账号ID</label>
                            <div class="layui-input-inline">
                                <input type="text" name="adminId" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">账号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="username" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">账号状态</label>
                            <div class="layui-input-inline">
                                <select id="enableStatus" name="enableStatus"  lay-search="">
                                    <option value="-1">全部</option>
                                    <option value="1">启用</option>
                                    <option value="0">禁用</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                            <button type="reset" class="layui-btn layui-btn-primary" id="data-reset-btn" > 重 置</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <span th:each="tb : ${toolbarButtons}" th:utext="${tb}"></span>

            </div>
        </script>

        <table class="layui-hide" id="adminTable" lay-filter="adminTableFilter"></table>

        <script type="text/html" id="adminTableBar">
            <span th:each="btn : ${rowButtons}" th:utext="${btn}"></span>
        </script>

    </div>
</div>
<script th:src="@{/lib/layui-v2.5.5/layui.js}" charset="utf-8"></script>
<script th:src="@{/lib/jquery-3.4.1/jquery-3.4.1.min.js}" charset="utf-8"></script>
<script>
    layui.config({
        base: basePath+'/lib/layui_ext/dtree/' //配置 layui 第三方扩展组件存放的基础目录
    }).extend({
        dtree: 'dtree' //定义该组件模块名
    }).use(['form', 'table','tree','dtree'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        var index;
        var tree = layui.tree;
        var loadding;
        var dtree = layui.dtree;
        var roleTree;
        var roleTreeDataArray = new Array();

        $.fn.serializeJson=function(){
            var serializeObj={};
            var array=this.serializeArray();
            var str=this.serialize();
            $(array).each(function(){
                if(serializeObj[this.name]){
                    if($.isArray(serializeObj[this.name])){
                        serializeObj[this.name].push(this.value);
                    }else{
                        serializeObj[this.name]=[serializeObj[this.name],this.value];
                    }
                }else{
                    serializeObj[this.name]=this.value;
                }
            });
            return serializeObj;
        };

        function getFormParam()
        {
            var formParam = $("#userSearchForm").serializeJson();
            return formParam;
        }


        $("#data-reset-btn").click(function(){
            $("#userSearchForm")[0].reset();
            layui.form.render();
        });



        table.render({
            elem: '#adminTable',
            url: "[[@{/}]]admin/list",
            method:'POST',
            where:getFormParam(),
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter',  {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            done:function(res, curr, count)
            {
            },
            cols: [
                [
                    {type: "checkbox", width: 50},
                    {field: 'id',  title: '主键'},
                    {field: 'username',  title: '账号'},
                    {field: 'adminId',  title: '账号ID'},
                    {field: 'appNames', title: '关联应用'},
                    {field: 'enableStatus', title: '账号状态',
                        templet: function (row) {
                            if(row.enableStatus == "1"){
                                return "启用"
                            }
                            return "禁用"
                        }},
                    {field: 'createDate',  title: '创建时间'},
                    {field: 'createAdminId',  title: '创建人ID'},
                    {title: '操作', minWidth: 300, toolbar: '#adminTableBar', align: "center"}
                ]
            ],
            limits: [15,30,100,200],
            limit: 15,
            page: true,
            skin: 'line'
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            table.reload('adminTable', {
                page: {
                    curr: 1
                }
                , where: data.field
            }, 'data');

            return false;
        });




        /**
         * toolbar监听事件
         */
        table.on('toolbar(adminTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加账号',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,

                    area: ['100%', '100%'],
                    content: "[[@{/admin/addPage}]]",
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('adminTable')
                    , data = checkStatus.data;
                if(data==null||data.length<=0)
                {
                    layer.msg("请选择要操作的记录");
                    return;
                }
                layer.confirm('确定删除账号?', function (index) {
                    $.ajax({
                        url:"[[@{/}]]admin/delete/ids",
                        contentType: "application/json; charset=utf-8",
                        type:'DELETE',
                        data:JSON.stringify(data),
                        success:function(data){
                            layer.msg(data.msg);

                            //执行搜索重载
                            table.reload('adminTable', {
                                page: {
                                    curr: 1
                                }
                                , where: data.field
                            }, 'data');

                        },
                        complete:function(data)
                        {
                            layer.close(index);
                        }
                    });
                });
            }
        });




        /**
         * 拿到所有选中节点的ID
         * @param data
         * @param idArray
         */
        function getCheckdNodeId(data,idArray)
        {
            for(var i=0;i<data.length;i++)
            {
                roleTreeDataArray.push(data[i]);
                if(data[i].state.checked==true)
                {
                    idArray.push(data[i].id);
                }
                if(data[i].children!=null&&data[i].children.length>0)
                {
                    getCheckdNodeId(data[i].children,idArray);
                }
            }
        }


        /**
         * 拿到指定节点对象
         */
        function getNodeObject(nodeId)
        {
            for(var i=0;i<roleTreeDataArray.length;i++)
            {
                if(roleTreeDataArray[i].id==nodeId)
                {
                    return roleTreeDataArray[i];
                }
            }
            return null;
        }


        /**
         * 拿到上级节点信息
         */
        function getParentNode(rolesArray,pid)
        {
            for(var i=0;i<roleTreeDataArray.length;i++)
            {

                if(roleTreeDataArray[i].id==pid)
                {
                    var exists=false;
                    //判断上级节点ID是否已经保存了
                    for(var j=0;j<rolesArray.length;j++)
                    {
                        if(rolesArray[j].id==pid) {
                            exists = true;
                        }
                    }
                    //避免上级节点ID重复保存两份
                    if(!exists)
                    {
                        rolesArray.push({roleId:roleTreeDataArray[i].roleId,appCode:roleTreeDataArray[i].appCode})
                    }
                    if(roleTreeDataArray[i].pid!=-1) {
                        //找到这个节点的上级节点
                        getParentNode(rolesArray, roleTreeDataArray[i].pid);
                    }
                }
            }
        }


        //监听表格复选框选择
        table.on('checkbox(adminTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(adminTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event == 'edit') {

                var index = layer.open({
                    title: '编辑用户',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,

                    area: ['100%', '100%'],
                    content: '[[@{/}]]admin/editPage/'+data.id
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event == 'delete') {
                layer.confirm('确定删除该账号?', function (index) {
                    $.ajax({
                        url:"[[@{/}]]admin/delete/"+data.id,
                        contentType: "application/json; charset=utf-8",
                        type:'DELETE',
                        success:function(data){
                            layer.msg(data.msg);

                            //执行搜索重载
                            table.reload('adminTable', {
                                page: {
                                    curr: 1
                                }
                                , where: data.field
                            }, 'data');

                        },
                        complete:function(data)
                        {
                            layer.close(index);
                        }
                    });
                });
            }else if (obj.event == 'role') {
                index = layer.open({
                    title: '选择角色',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,

                    area: ['20%', '60%'],
                    btn: ['确定'],
                    content: "<ul id='roleTree' class='dtree' data-id='0'></ul>",
                    success:function(layero){
                        loadding = layer.load();
                        $.ajax({
                            url:"[[@{/}]]role/query/admin/role/tree",
                            contentType: "application/json; charset=utf-8",
                            type:'POST',
                            data:JSON.stringify({adminId:data.adminId}),
                            success:function(data){
                                if(data.code==1)
                                {
                                    //已选择节点
                                    roleTreeDataArray = new Array();
                                    var idArray = new Array();
                                    getCheckdNodeId(data.data,idArray);
                                    roleTree = dtree.render({
                                        elem: "#roleTree",//html中的id值
                                        data:data.data,
                                        checkbarType: "no-all",
                                        width:'100%',
                                        checkbar: true,  //开启复选框
                                        checkbarData: "choose",// 记录选中（默认）， "change"：记录变更， "all"：记录全部， "halfChoose"："记录选中和半选（V2.5.0新增）"
                                        done: function (res, $ul, first) {
                                            if (first) {
                                                if(idArray!=null&&idArray.length>0) {
                                                    dtree.chooseDataInit("roleTree", idArray.join(",")); //"001001,001002"被选中的子节点id
                                                    dtree.initNoAllCheck("roleTree");// 反选半选状态(原始数据中父节点的选中或半选状态并没有被带上)
                                                }
                                            }

                                        }
                                    });
                                }
                            },
                            complete:function()
                            {
                                layer.close(loadding);
                            }
                        });

                    },
                    yes: function(index, layero){
                        var selectNodes = roleTree.getCheckbarNodesParam("roleTree");
                        if(selectNodes==null||selectNodes.length<=0)
                        {
                            layer.msg("请选择角色");
                            return false;
                        }
                        var rolesArray =  new Array();
                        for (var i = 0; i < selectNodes.length; i++) {
                            var selectNodeObject = getNodeObject(selectNodes[i].nodeId);
                            rolesArray.push({roleId:selectNodeObject.roleId,appCode:selectNodeObject.appCode});
                            getParentNode(rolesArray,selectNodeObject.pid);
                        }

                        $.ajax({
                            url: "[[@{/}]]admin/connect/roles",
                            contentType: "application/json; charset=utf-8",
                            type: 'POST',
                            data: JSON.stringify({roles:rolesArray,adminId:data.adminId}),
                            success: function (data) {
                                if (data.code == 0) {
                                    layer.msg(data.msg);
                                    return false;
                                }
                                layer.close(index);
                            }
                        });
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });

            }if (obj.event == 'orgnazition') {

                var index = layer.open({
                    title: '选择组织机构',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,

                    area: ['100%', '100%'],
                    content: '[[@{/}]]admin/selectOrgnazitionPage/'+data.adminId
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            }else if (obj.event == 'password') {

                var index = layer.open({
                    title: '修改密码',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,

                    area: ['100%', '100%'],
                    content: '[[@{/}]]admin/passwordPage/'+data.id
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            }
        });

    });
</script>

</body>
</html>